package com.changgou.controller;

import com.changgou.common.pojo.Page;
import com.changgou.search.feign.SkuFeign;
import com.changgou.search.pojo.SkuInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.Map;

@Controller
@RequestMapping("/search")
public class SkuController {
    @Autowired
    private SkuFeign skuFeign;
    /**查询的实现*/
    @GetMapping(value = "/list")
    public String search(@RequestParam(required = false)Map<String,String> searchMap, Model model){
        // 调用搜索微服务
        Map<String,Object> searchMa = skuFeign.search(searchMap);
        //封装查询的数据
        model.addAttribute("resultMap", searchMa);
        Page<SkuInfo> pageInfo =new  Page<SkuInfo>(
                Long.parseLong(searchMa.get("total").toString()),
               Integer.parseInt(searchMa.get("pageNumber").toString()+1),
                Integer.parseInt(searchMa.get("pageSize").toString())
        );
        model.addAttribute("searchMap", searchMap);
        model.addAttribute("pageInfo", pageInfo);
        //获得url
        String[] urls = url(searchMap);
        model.addAttribute("url", urls[0]);
        model.addAttribute("sortUrl", urls[1]);
        //返回页面
        return  "search";
    }

    /**
     * 拼接url参数
     * @param searchMap
     * @return
     */
    public String[] url(Map<String,String> searchMap){
     String url="/search/list";//初始化地址
        String sortUrl="/search/list";// 排序地址
     // 条件不为空
     if (searchMap!=null && searchMap.size()>0){
         // 给字符串加？?keywords=华为
         url +="?";
         // 循环map
      for (Map.Entry<String, String> entry : searchMap.entrySet()) {
          String key = entry.getKey();
          String value = entry.getValue();
          if (key.equalsIgnoreCase("pageNum")){
              continue;
          }
          url+= key +"="+ value+"&";
          //排序参数跳过
          if (key.equalsIgnoreCase("sortFiled") || key.equalsIgnoreCase("sortRule")){
             continue;
          }
          sortUrl+=key +"="+ value+"&";
      }
      // 去掉最后一个&
        url = url.substring(0, url.length() - 1);
     }
        return  new String[]{url,sortUrl};
    }
}
